<template>
  <div class="module_">
    <div class="flex-align-start">
      <el-upload
        class="tx-c mr8 mt4"
        action="/"
        :on-change='onChange'
        :auto-upload="false"
        ref="upload"
        accept='.xlsx,.xls,.csv'
        >
        <el-button size="small" type="primary">选择文件</el-button>
        <div slot="tip" class="el-upload__tip">只能上传.xlsx,.xls,.csv文件</div>
      </el-upload>
      <el-select v-model="options.data_type" placeholder="请选择上传文件类型" class="mr8">
        <el-option
          v-for="item in uploadType"
          :key="item.value"
          :label="item.label"
          :value="item.value">
        </el-option>
      </el-select>
      <el-date-picker
        class="mr8"
        v-model="options.date"
        type="month"
        placeholder="选择文件统计时间">
      </el-date-picker>
      <p class="mt4">
        <el-button size="small" type="success" @click="submitUpload" >上传文件</el-button>
      </p>
    </div>
    
  </div>
</template>

<script>
import {ApidatasImport} from '@/api'
import {getNowFormatDate} from '@/utils'
import {uploadType} from '@/assets/js'
import XLSX from 'xlsx'
export default {
  data(){
    return{
      uploadType,
      options:{
        file:'',
        data_type:null,
        date:''
      }
    }
  },
  methods:{
    onChange(files){
      this.options.file = files.raw
    },
    submitUpload(){
      if(!this.options.file){
        this.$message.error('请选择文件！')
        return
      }
      if(!this.options.data_type){
        this.$message.error('请选择上传文件类型！')
        return
      }
      if(!this.options.date){
        this.$message.error('请选择上传文件所统计的时间！')
        return
      }
      const loading = this.$loading({
        lock: true,
        text: '文件上传中，请稍等！',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      this.options.date = getNowFormatDate(this.options.date,2)
      const formData = new FormData()
      const that = this
      formData.append("file", this.options.file);
      formData.append("data_type", this.options.data_type);
      formData.append("date", this.options.date);

      ApidatasImport(formData,{
        headers:{'Content-Type':'multipart/form-data'},
        timeout: 5 * 60 * 1000,
        onUploadProgress(progressEvent){
          let complete = (progressEvent.loaded / progressEvent.total * 100 | 0) + '%'
          console.log(complete)
        }
      }).then(res => {
        loading.close();
        this.$refs.upload.clearFiles()
        this.$message.success('文件上传成功,成功上传' + res.data.import_count + '条数据')
      }).catch(()=>{
        loading.close();
        this.$message.error('文件上传失败')
      })
    }
  }
}
</script>

<style>

</style>